package com.jnevision.personalattendance.controller;


import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.api.ApiController;
import com.baomidou.mybatisplus.extension.api.R;
import com.jnevision.personalattendance.model.PersonalAttendance;
import com.jnevision.personalattendance.service.PersonalAttendanceServiceImpl;
import com.jnevision.user.model.User;
import com.jnevision.user.service.UserServiceImpl;
/**
 * <p>
 * 人员考勤 前端控制器
 * </p>
 *
 * @author gavin
 * @since 2019-07-21
 */

@RestController
@RequestMapping("/personalattendances")
public class PersonalAttendanceController extends ApiController {

	
	@Autowired
	private PersonalAttendanceServiceImpl personalAttendanceServiceImpl;
	
	@Autowired
	private UserServiceImpl userServiceImpl;
	
	@GetMapping("/groupId")
	public List<PersonalAttendance> list(String groupId){
		List<PersonalAttendance> list = this.personalAttendanceServiceImpl.list(new QueryWrapper<PersonalAttendance>().eq("group_id", groupId));
		
		list.forEach(pa->{
			User byId = userServiceImpl.getById(pa.getUserId());
			
			if (null!=byId&&StringUtils.isNotEmpty(byId.getName())) {
				pa.setUserName(byId.getName());	
			}
		});
		
		return list;
	}
	
	@PostMapping
	public R<Boolean> save(@RequestBody List<PersonalAttendance> list){
		
		List<PersonalAttendance> list2 = this.personalAttendanceServiceImpl.list(new QueryWrapper<PersonalAttendance>().eq("group_id", list.get(0).getGroupId()));
		
		List<String> collect = list2.stream().map(PersonalAttendance::getId).collect(Collectors.toList());
		
		if (CollectionUtils.isNotEmpty(collect)) {
			this.personalAttendanceServiceImpl.removeByIds(collect);
		}

		list.forEach(action->{
			action.setId(UUID.randomUUID().toString().replace("-", ""));
		});
		
		return this.success(this.personalAttendanceServiceImpl.saveBatch(list));
	}
}

